package com.aw.baselib.util.update;

import android.content.Context;

import com.aw.baselib.R;
import com.aw.baselib.base.AwBaseApplication;
import com.aw.baselib.util.AwAppUtils;
import com.aw.baselib.util.AwLog;
import com.aw.baselib.util.AwVersionUtil;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author : hzw
 * @date : 2021/6/4
 */
public class AwUpdateCheckUtil {

    public static final String URL_UPDATE = "https://sirun-app.oss-cn-beijing.aliyuncs.com/Weima/android/demoNew/version.json";


    public static void checkUpdate(final Context context,  final IUpdateCheckCallback callback) {
        if(context == null || callback == null) {
            return;
        }
        OkHttpClient.Builder builder = Okhttp3Manager.getOkhttp();
        OkHttpClient mOkHttpClient = builder.build();
        Request request = new Request.Builder()
                //                .cacheControl(CacheControl.FORCE_NETWORK) //取消缓存读取
                .method("GET", null)
                .url(URL_UPDATE)
                .build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                AwLog.d("checkUpdate onFailure: " + e.getMessage());
                callback.checkFail(AwBaseApplication.getInstance().getString(R.string.update_hint_check_fail));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.cacheResponse()) {
                    AwLog.d("checkUpdate onResponse cacheResponse: " + response.cacheResponse().toString());
                } else {
                    String body = response.body().string();
                    AwLog.d("checkUpdate onResponse networkResponse: " + response.networkResponse().toString() + " ,body: " + body);
                    UpdateBean bean = new Gson().fromJson(body, UpdateBean.class);
                    if(bean != null && AwVersionUtil.compareVersions(AwAppUtils.getAppVersionInfo(context, AwAppUtils.TYPE_VERSION.TYPE_VERSION_NAME), bean.getAppVersion()) > 0) {
                        AwLog.d("checkUpdate onResponse networkResponse 需升级");
                        callback.checkSuccess(bean);
                    } else {
                        AwLog.d("checkUpdate onResponse networkResponse 不需升级");
                        callback.checkFail(AwBaseApplication.getInstance().getString(R.string.update_hint_newest));
                    }
                }
            }
        });
    }
}
